<template>
  <div class="org-member-tree h100">
    <div class="treeTitleDiv" v-if="showTitle">
      <div class="treeTitle">台账结构</div>
      <el-button
        v-if="showSearch"
        size="small"
        style="margin-left: 10px"
        type="text"
        @click="showDialog = true"
        >高级搜索</el-button
      >
    </div>
    <div
      class="filter__box showSearch"
      :style="{ width: showTitle ? '100%' : '70%' }"
    >
      <el-select
        ref="selectItem"
        size="mini"
        filterable
        clearable
        remote
        default-first-option
        class="w100"
        v-model="filterText"
        :multiple="false"
        :placeholder="'请输入选择'"
        :remote-method="
          (query) => {
            getEquipmentBrand(query);
          }
        "
        @change="(val) => brandSelectChange(val)"
        v-loadmore="(val) => load()"
      >
        <el-option
          v-for="(optionItem, index) in option"
          :key="index"
          :label="optionItem.label"
          :value="optionItem.value"
        ></el-option>
      </el-select>
    </div>
    <div class="tree__box">
      <el-tree
        :props="props"
        @node-click="treeNodeClick"
        highlight-current
        :filter-node-method="filterNode"
        :load="loadNode"
        :data="treedata"
        :default-expanded-keys="expandKeys"
        :default-checked-keys="checkedKeys"
        :draggable="draggable"
        @node-drag-end="handleDragEnd"
        @check="checkClick"
        :check-strictly="checkStrictly"
        :expand-on-click-node="clickExpand"
        :node-key="nodeKey"
        :show-checkbox="showCheckbox"
        lazy
        accordion
        ref="tree"
      >
        <span class="custom-tree-node" slot-scope="{ node, data }">
          <span>{{ data.name }}</span>
          <!-- <span v-if="data.level==3" class="number">({{data.childrenNum}})</span> -->
          <span>
            <el-button
              v-if="btnArr.indexOf('detail') != -1"
              type="text"
              @click.stop="() => TNodeDetail(node, data)"
              class="btnIcon"
              icon="el-icon-document"
            ></el-button>
            <el-button
              v-if="btnArr.indexOf('delete') != -1"
              type="text"
              @click.stop="() => TNodeDel(node, data)"
              class="btnIcon"
              icon="el-icon-delete"
            ></el-button>
          </span>
        </span>
      </el-tree>
    </div>
    <dialogPublic
      title="高级搜索"
      :show.sync="showDialog"
      :fullscreen="true"
      appendTobody
      @doSubmit="updateData"
      @doClose="resetInfo"
      @closeDialog="showDialog = false"
      :sameClose="false"
      noFootBtn
      :btnText="['重置']"
      singleClose
    >
      <div class="advanceSearch">
        <list-table-new
          v-bind="tableSetting"
          ref="tableRef"
          @changeInput="changeInput"
        ></list-table-new>
      </div>
    </dialogPublic>
  </div>
</template>
 <script>
import {
  lazyClassifyTree, //获取设备台账树
  queryList, //根据设备名称模糊查询
  getParentIdsApi, //获取某个节点的所有父节点
  getLeftUpperApi,
  getEquipment,
  advancedEquipmentQuery,
  searchParamsByName,
} from "@/api/equipmentLedger/equipmentManage";
import { classStandardDetail } from "@/api/standardManagement/acountManagement.js";

export default {
  props: {
    itemArrs: {
      type: Array,
      default: () => {
        return [];
      },
    },
    btnArr: {
      type: Array,
      default: () => {
        return [];
      },
    },
    checkedKeys: {
      type: Array,
      default: () => {
        return [];
      },
    },
    currentNode: {
      type: Object,
      default: () => {
        return {};
      },
    },

    filterConfig: {
      type: Object,
      default: () => {
        return {};
      },
    },
    nodeKey: {
      type: String,
      default: "id",
    },
    //指定展开的节点id
    expandNode: {
      type: String,
      default: "id",
    },
    //展示标题
    showTitle: {
      type: Boolean,
      default: true,
    },
    //显示高级搜索
    showSearch: {
      type: Boolean,
      default: true,
    },
    //复选框限制选择的个数
    optionalNum: {
      type: Number,
      default: 0,
    },
    draggable: {
      type: Boolean,
      default: false,
    },
    //用于位置移动
    moveNode: {
      type: Boolean,
      default: false,
    },
    /* 是否点击展开 */
    clickExpand: {
      type: Boolean,
      default: false,
    },
    /* 是否显示选择框 */
    showCheckbox: {
      type: Boolean,
      default: false,
    },
    /* 是否遵循父子不互相关联的做法 */
    checkStrictly: {
      type: Boolean,
      default: false,
    },
  },
  inject: ['getHideRepeatNode', 'getSelectedNodeList'],
  data() {
    return {
      lineIndex: 1,
      list: [
        {
          label: "身份信息",
          value: "identityInfo",
        },
        {
          label: "基本参数",
          value: "basicParameter",
        },
        {
          label: "技术参数",
          value: "technicalParameter",
        },
      ],
      identityList: [
        {
          label: "名称",
          value: "name",
          enterType: "box",
        },
        {
          label: "编码",
          value: "code",
          enterType: "box",
        },
        {
          label: "设备分类",
          value: "type",
          enterType: "radio_deviceClassify",
          dataType: "text",
        },
        {
          label: "关联组织",
          value: "dept",
          enterType: "radio_org",
          dataType: "text",
        },
        {
          label: "所属层级",
          value: "level",
          enterType: "radio",
          dataText: JSON.stringify(
            this.$store.getters.dirtData("equipment_level")
          ),
          dataType: "text",
        },
      ],
      basicList: [],
      technicalList: [],
      showDialog: false,
      tableSetting: {
        showSearchLabel: false,
        showSearchBtn: true,
        showCustomBtn: false, //显示自定义列
        showFilterBtn: false, //显示过滤器
        // 搜索框
        searchObj: {
          searchMethod: (params, sortStr) => {
            this.getTableData(params, sortStr);
          },
          queryData: {
            page: 1,
            pageSize: 15,
          },
          searchArr: [
            {
              type: "select",
              model: "list-1-1",
              disabled: false,
              option: [],
            },
            {
              type: "select",
              model: "list-1-2",
              disabled: false,
              option: [],
              remote: true,
              remoteMethod: (val) => {
                console.log(val);
              },
            },
            {
              type: "select",
              model: "list-1-3",
              idsStr: "",
              disabled: false,
              option: [],
            },
            {
              type: "icon-button",
              icon: "el-icon-plus",
              methods: () => {
                this.addItem();
              },
            },
          ],
        },
        // 表头
        column: [
          {
            label: "设备名称",
            prop: "name",
          },
          {
            label: "设备分类",
            prop: "typeName",
          },
          {
            label: "设备全路径",
            prop: "fullPathName",
          },
          {
            label: "设备管理单位",
            prop: "deptName",
          },
        ],
        // 表格方法
        tableMethods: {
          //点击行的方法
          rowClick: (val) => {
            this.getNodeDetails(val.id, 1);
            this.showDialog = false;
          },
        },
      },
      treedata: [],
      rootNode: {},
      defaultNode: {},
      rootResolve: null,
      node: null,
      isChild: false,
      loadNodeData: [],
      option: [],
      count: 1,
      show: false,
      title: "添加节点",
      parentNum: 0,
      filterText: "",
      firstParentNode: "",
      props: {
        label: "name",
        children: "children",
        isLeaf: "isLeaf",
        disabled: 'disabled'
      },
      expandKeys: [],
      currentId: "",
      selectNode: {},
      toLevel: 0,
      query: "",
      paramType: "",
      currentIndex: 0,
      selectedNodeList: []
    };
  },
  created() {
    this.selectedNodeList = this.getSelectedNodeList()
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    },
    filterLabel(val) {
      this.$refs.tree.filter(val);
    },
    //展开的节点
    // expandNode(val) {
    //   this.getNodeDetails(val);
    // },
    expandNode: {
      immediate: true,
      handler(val) {
        this.getNodeDetails(val);
      }
    },
    rootNode: {
      deep: true,
      handler(newVal) {
        // 隐藏已经新增的节点
        if(this.getHideRepeatNode()) {
          const rootMap = new Map()
          this.recursive([newVal], rootMap)
          // console.log(rootMap);
        }
      }
    }
  },
  mounted() {
    this.resetInfo();
  },
  methods: {
    recursive(rootNode, map) {
      for(let node of rootNode) {
        map.set(node.id, node)
        if(node.childNodes && node.childNodes.length > 0) {
          this.recursive(node.childNodes, map)
        }
      }
    },
    //输入类型-转换
    changeType(type) {
      let inputType = "";
      switch (type) {
        case "radio":
          inputType = "radio";
          break; //单选
        case "multi":
          inputType = "select";
          break; //多选
        case "date_day":
          inputType = "date";
          break; //日期
        case "brand":
          inputType = "select";
          break; //厂商
        case "trademark":
          inputType = "equipmentBrand";
          break; //品牌
        case "date_time":
          inputType = "datetime";
          break; //选日期时间
        case "box":
          inputType = "text";
          break; //文本框
        case "location":
          inputType = "text";
          break; //选位置
        case "radio_org":
          inputType = "dept";
          break; //组织单选
        case "multi_org":
          inputType = "dept";
          break; //选组织-多选
        case "radio_man":
          inputType = "user";
          break; //设备分类-单选
        case "radio_deviceClassify":
          inputType = "deviceClassify";
          break; //选人-单选
        case "multi_man":
          inputType = "user";
          break; //选人-多选
      }
      return inputType;
    },
    //更改下拉框
    changeInput(model, searchForm) {
      let index = this.tableSetting.searchObj.searchArr.findIndex((item) => {
        return item.model == model;
      });
      let column = model[model.length - 1];
      if (column == 1) {
        let list = [];
        if (searchForm[model] == "identityInfo") {
          list = this.identityList;
          this.tableSetting.searchObj.searchArr[index + 1].option = list;
        } else if (searchForm[model] == "basicParameter") {
          this.paramType = "1";
          this.getParamsList("");
        } else if (searchForm[model] == "technicalParameter") {
          this.paramType = "2";
          this.getParamsList("");
        }
        this.$refs.tableRef.setSearchItem(`list-${index + 1}-2`);
        this.$refs.tableRef.setSearchItem(`list-${index + 1}-3`);
        this.currentIndex = index;
      } else if (column == 2) {
        let i = this.tableSetting.searchObj.searchArr[index].option.find(
          (item) => {
            return item.value == searchForm[model];
          }
        );
        let inputType = this.changeType(i.enterType);
        inputType = inputType == "radio" ? "select" : inputType;
        let item = {
          model: i.value + "Name",
          idsStr: i.value + "Id",
          type: inputType,
        };
        if (["radio", "select"].includes(inputType)) {
          item.model = i.paramId + "Id";
          item.methods = (obj, data) => {
            //paramResult存value即code;paramValue存lable即name;
            if (i.enterType == "multi") {
              let str = [];
              obj.map((k) => {
                if (k) {
                  str.push(k.label);
                }
              });
              data[i.paramId] = str.toString();
            } else {
              data[i.paramId] = obj.label;
            }
          };
          delete item.idsStr;
          if (i.dataText && i.dataText != "") {
            let option = $.parseJSON(i.dataText);
            item.option = option;
          } else {
            //没有选项值，用数据字典的值
            if (i.enterType == "brand") {
              //选厂商
              item.option = this.$store.getters["vendorList"];
            }
          }
        }
        this.$refs.tableRef.setSearchItem(`list-${index}-3`);
        this.tableSetting.searchObj.searchArr[index + 1].type = item.type;
        this.tableSetting.searchObj.searchArr[index + 1].idsStr = item.idsStr;
        this.tableSetting.searchObj.searchArr[index + 1].option = item.option;
      }
    },
    //获取分类标准详情
    getParamTable(id) {
      classStandardDetail({ id }).then(
        (res) => {
          if (res.code == 200) {
            this.list1 = [
              {
                label: "身份信息",
                value: "identityInfo",
              },
            ];
            if (
              res.data.typeGroupParamsList &&
              res.data.typeGroupParamsList.length
            ) {
              this.list1.push({
                label: "基本参数",
                value: "basicParameter",
              });
              this.basicList = res.data.typeGroupParamsList.map((item) => {
                return {
                  label: item.paramName,
                  value: item.id,
                  enterType: item.enterType,
                  dataType: item.dataType,
                  dataText: item.dataText,
                };
              });
            } else {
              this.basicList = [];
            }
            if (res.data.typeParamsList && res.data.typeParamsList.length) {
              this.list1.push({
                label: "技术参数",
                value: "technicalParameter",
              });
              this.technicalList = res.data.typeParamsList.map((item) => {
                return {
                  label: item.paramName,
                  value: item.id,
                  enterType: item.enterType,
                  dataType: item.dataType,
                  dataText: item.dataText,
                };
              });
            } else {
              this.technicalList = [];
            }
          }
        },
        (error) => {
          this.$message.error(error);
        }
      );
    },
    //重置
    resetInfo() {
      this.$set(this.tableSetting, "tableData", []);
      this.$set(this.tableSetting, "totalNumber", 0);
      this.tableSetting.searchObj.searchArr = [
        {
          type: "select",
          model: "list-1-1",
          disabled: false,
          option: this.list,
        },
        {
          type: "select",
          model: "list-1-2",
          disabled: false,
          option: [],
          remote: true,
          filterable: true,
          remoteMethod: (val) => {
            console.log(val);
            this.getParamsList(val);
          },
        },
        {
          type: "select",
          model: "list-1-3",
          disabled: false,
          option: [],
        },
        {
          type: "icon-button",
          icon: "el-icon-plus",
          methods: () => {
            this.addItem();
          },
        },
      ];
      if (this.$refs.tableRef) {
        this.$refs.tableRef.initSearchData({ page: 1, pageSize: 15 });
      }
    },
    addItem() {
      let l = this.tableSetting.searchObj.searchArr.length;
      if (l >= 15) {
        this.$message.warning("筛选条件已达上限");
      } else {
        this.lineIndex++;
        let index = this.lineIndex;
        this.tableSetting.searchObj.searchArr.splice(
          l,
          0,
          {
            type: "select",
            model: "list-" + this.lineIndex + "-1",
            option: this.list,
          },
          {
            type: "select",
            model: "list-" + this.lineIndex + "-2",
            option: [],
            disabledOp: (val, option) => {
              return val.disabled;
            },
            remote: true,
            filterable: true,
            remoteMethod: (val) => {
              console.log(val);
              this.getParamsList(val);
            },
          },
          {
            type: "select",
            model: "list-" + this.lineIndex + "-3",
            idsStr: "",
            option: [],
          },
          {
            type: "icon-button",
            methods: () => {
              let ItemIndex = this.tableSetting.searchObj.searchArr.findIndex(
                (item) => {
                  return item.model == "list-" + index + "-1";
                }
              );
              this.tableSetting.searchObj.searchArr.splice(ItemIndex, 4);
            },
          }
        );
      }
    },
    //模糊匹配基本参数或技术参数
    async getParamsList(val) {
      let params = {
        paramName: val,
        paramType: this.paramType,
      };
      let res = await searchParamsByName(params);
      let option = res.data.map((item) => {
        return {
          label: item.paramName,
          value: item.paramName,
          enterType: item.enterType,
          dataType: item.dataType,
          dataText: item.dataText,
        };
      });
      this.tableSetting.searchObj.searchArr[this.currentIndex + 1].option =
        option;
    },
    updateData() {
      this.$refs.tableRef.searchData();
    },
    // 查询表格数据
    async getTableData(params, sortStr) {
      let queryData = {
        page: params.page,
        pageSize: params.pageSize,
      };
      queryData.params = [];
      if (this.tableSetting.searchObj.searchArr) {
        this.tableSetting.searchObj.searchArr.forEach((item, index) => {
          let paramObj = {
            paramId: "",
            paramValue: "",
            paramResult: "",
            paramType: "",
            paramName: "",
          };
          if (index === 1 || index === 5 || index === 9 || index === 13) {
            if (
              params[this.tableSetting.searchObj.searchArr[index - 1].model] ==
              "identityInfo"
            ) {
              //身份信息
              let key = this.tableSetting.searchObj.searchArr[index + 1].idsStr;
              if (params[key]) {
                queryData[key] = params[key];
              } else {
                queryData[params[item.model]] =
                  params[
                    this.tableSetting.searchObj.searchArr[index + 1].model
                  ];
              }
            } else {
              let objId = params[item.model];
              let paramValue =
                params[this.tableSetting.searchObj.searchArr[index + 1].model];
              let objResult =
                params[this.tableSetting.searchObj.searchArr[index + 1].idsStr];
              let objType =
                params[this.tableSetting.searchObj.searchArr[index - 1].model];
              if (this.tableSetting.searchObj.searchArr[index + 1].option) {
                objResult = paramValue;
                paramValue = "";
              } else {
                objResult = "";
              }
              if (objId) {
                paramObj.paramName = objId;
              }
              if (objType) {
                paramObj.paramType = objType == "basicParameter" ? "1" : "2";
              }
              if (paramValue) {
                paramObj.paramValue = paramValue;
              } else if (objResult) {
                paramObj.paramResult = objResult;
              }
              if (
                paramObj.paramName &&
                (paramObj.paramValue || paramObj.paramResult)
              ) {
                queryData.params.push(paramObj);
              }
            }
          }
        });
      }
      advancedEquipmentQuery(queryData)
        .then((list) => {
          this.$set(this.tableSetting, "tableData", list.data.list);
          this.$set(this.tableSetting, "totalNumber", list.data.total);
        })
        .catch((e) => {
          this.$set(this.tableSetting, "tableData", []);
          this.$set(this.tableSetting, "totalNumber", 0);
        });
    },
    getNodeDetails(val, flag) {
      val && getEquipment(val).then((res) => {
        let node = res.data;
        node.basicParams = null;
        node.children = null;
        node.techParams = null;
        node.params = [];
        this.defaultNode = node;
        if (flag) {
          this.updataData(node);
        }
      });
    },
    setDefaultNode(node) {
      this.defaultNode = node;
    },
    //设备列表查询
    async getEquipmentBrand(query, item) {
      this.query = query;
      if (query !== "") {
        let form = {
          name: query,
          page: 1,
          pageSize: 20,
        };
        let res = await queryList(form);
        let data = res.data.list || [];
        data.map((i) => {
          i.label = i.name;
          i.value = i.id;
        });
        this.option = data;
        this.count = 1;
      }
    },
    //设备下拉选择回传
    async brandSelectChange(val) {
      if (val) {
        this.$forceUpdate();
        let obj = this.option.find((i) => i.value == val);
        this.option = [obj];
        this.query = "";
        this.handleSelect(obj);
      } else {
        this.option = [];
        this.query = "";
      }
    },
    //设备懒加载

    async load() {
      let form = {
        name: this.query,
        page: (this.count += 1),
        pageSize: 20,
      };
      let res = await queryList(form);
      let data = res.data.list || [];
      data.map((i) => {
        i.label = i.name;
        i.value = i.id;
      });
      this.option = this.option.concat(data);
    },
    querySearch(queryString, cb) {
      var list = [{}];
      searchByNameApi(queryString)
        .then((res) => {
          if (res.code == 200) {
            for (let i of res.data) {
              i.value = i.name; //将想要展示的数据作为value
            }
            //大小写匹配
            let restaurants = [...res.data];
            var results = queryString
              ? restaurants.filter(this.createStateFilter(queryString))
              : restaurants;
            cb(results);
          }
        })
        .catch((error) => {
          this.$message.error(error.description);
        });
    },
    createStateFilter(queryString) {
      return (state) => {
        return (
          state.value.toLowerCase().indexOf(queryString.toLowerCase()) !== -1
        );
      };
    },
    //点击搜索结果
    handleSelect(item) {
      let currentId = item.id;
      this.selectNode = item;
      this.toLevel = item.level;
      this.treedata = [];
      //this.refreshLoad();
      this.loadNode(this.rootNode, this.rootResolve);
      this.expandTreeNode(item);
    },
    //展开节点
    expandTreeNode(arr1, isSave) {
      getParentIdsApi(arr1.id)
        .then((res) => {
          if (res.code == 200) {
            let ids = res.data;
            ids.push(arr1.id);
            this.parentNum = res.data.length;
            let items = [];
            this.expandKeys = [];
            this.expandKeys = ids.reverse();
            if (isSave) {
              //不是第一次加载，保存数据后刷新树，数据保留到当前节点的上一层节点，同时展开父节点下的数据
              this.rootNode.childNodes = this.nextNode(
                this.rootNode.childNodes,
                1
              );
            }
          }
        })
        .catch((err) => {
          this.$message.error(err.description);
        });
    },
    //保留父节点上的数据
    nextNode(data, num) {
      let keys = this.expandKeys.reverse();
      for (let i in data) {
        if (num == this.parentNum - 2) {
          if (keys.includes(data[i]["key"])) {
            //找到父节点
            this.firstParentNode = data[i];
            data[i].childNodes = [];
            data[i].loaded = false;
            return data;
          }
        } else if (keys.includes(data[i]["key"])) {
          data[i].childNodes = this.nextNode(data[i].childNodes, num + 1);
          return data;
        }
      }
    },
    familyTree(list, id) {
      for (let i in list) {
        if (list[i].id == id) {
          return [list[i]];
        }
        if (list[i].children) {
          let node = this.familyTree(list[i].children, id);
          if (node !== undefined) {
            return node.concat(list[i]);
          }
        }
      }
    },
    //刷新懒加载的数据
    refreshLoad() {
      this.loadNodeData.forEach((item) => {
        this.loadNode(item.node, item.resolve);
      });
    },
    //确定
    doSubmit() {
      this.$refs.editFormDialog.getFormData().then((res) => {
        this.$emit("save", res);
      });
    },
    //关闭
    doClose() {
      this.show = false;
    },
    handleDragEnd(draggingNode, dropNode, dropType, ev) {
      this.$confirm("确定上移此节点吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let draggingNodeId = draggingNode.data.id;
          let dropNodeId = dropNode.data.parentId;
          let targetId = dropNode.data.id;
          let param = {
            id: draggingNodeId,
            targetId: targetId,
            dropType: dropType,
          };
          batchUpdateDeviceTree(param)
            .then((res) => {
              if (res.code == 200) {
                let node = this.$refs.tree.getNode(dropNode.data.id); // 通过节点id找到对应树节点对象
                node.parent.loaded = false;
                node.parent.expand(); // 主动调用展开节点方法，重新查询该节点下的所有子节点
                //this.loadNode(this.node,this.resolve)
                this.$message.success(res.description);
              }
            })
            .catch((err) => {
              this.$message.error(err.description);
            });
        })
        .catch((e) => {
          let node = this.$refs.tree.getNode(dropNode.data.id); // 通过节点id找到对应树节点对象
          let dragNode = this.$refs.tree.getNode(draggingNode.data.id);
          node.parent.loaded = false;
          node.parent.expand(); // 主动调用展开节点方法，重新查询该节点下的所有子节点
          dragNode.parent.loaded = false;
          dragNode.parent.expand();
          this.$message.warning("取消移动！");
        });
    },
    //上移节点
    TNodeUp(node, data) {
      this.$emit("upNode", data);
    },
    //下移节点
    TNodeDown(node, data) {
      this.$emit("downNode", data);
    },
    //新增字节点
    TNodeAdd(node, data) {
      this.show = true;
      this.formConfigDialog.itemArr = this.itemArrs;
    },
    //编辑
    TNodeEdit(node, data) {
      this.show = true;
      this.editFormDataDialog = Object.assign({}, data);
    },
    //删除
    TNodeDel(node, data) {
      this.$confirm("此操作将删除【" + data.name + "】, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let param = {
            deleteId: data.id,
          };
          deleteFormData(param).then((res) => {
            if (res.data == 1) {
              this.currentTreeNode = {};
              this.$refs.tree.remove(data);
              this.$message.success("删除成功！");
            } else {
              this.$message.warning("无法删除非叶子节点！");
            }
          });
        })
        .catch((e) => {});
    },
    //详情
    TNodeDetail(node, data) {
      this.$emit("detail", data);
    },
    //过滤搜索
    filterNode(value, data) {
      if (value) return true;
      let label = data[this.props.label];
      return label.indexOf(value) !== -1;
    },
    //点击树节点
    treeNodeClick(node) {
      if(this.getHideRepeatNode() && node.cantSelected) {
        this.$message.warning(`您已新建过'${node.label}'节点，请勿重复新建，如需修改该节点，请在参数明细列表中编辑！`)
        
      }
      if (node && node.id && this.$refs.tree) {
        this.currentId = node.id || "";
        let selectNode = this.$refs.tree.getNode(node.id).data;
        this.$refs.tree.setCurrentKey(node.id); //设置当前选择的节点
        this.$emit("handleClickTree", selectNode);
      }
    },
    //禁用树节点
    async setDisabledNode(data, resolve) {
      let parentIds = [];
      if (this.isChild) {
        //是否已经到了子层级
        if (parentIds.length == 0) {
          let res = await getParentIdsApi(data[0].id);
          parentIds = res.data || [];
        }
        if (parentIds.includes(this.currentNode.id)) {
          data.map((i) => {
            i.disabled = true;
          });
        } else {
          data.map((i) => {
            if (i.floor > this.currentNode.floor) {
              i.disabled = true;
            }
          });
        }
      } else {
        for (let item of data) {
          if (item.id == this.currentNode.id) {
            item.disabled = true;
            this.isChild = true;
            parentIds = [];
          }
          if (this.currentNode.floor) {
            if (item.floor > this.currentNode.floor) {
              item.disabled = true;
            }
          }
        }
      }
      if (resolve) {
        let treeData = [];
        data.map((i) => {
          i.label = i.name;
          i.isLeaf = i.hasChildren ? false : true;
          treeData.push(i);
        });
        resolve(treeData);
      }
    },
    //默认进来加载数据
    loadNode(node, resolve) {
      //如果展开第一级节点，从后台加载一级节点列表
      if (node.level == 0) {
        this.rootNode = node;
        this.rootResolve = resolve;
        this.loadfirstnode(resolve);
      }
      //如果展开其他级节点，动态从后台加载下一级节点列表
      if (node.level >= 1) {
        this.node = node;
        this.resolve = resolve;
        this.loadchildnode(node, resolve);
      }
      this.$nextTick(() => {
        this.$refs.tree.setCurrentKey(this.currentId);
      });
    },
    //加载第一级节点
    loadfirstnode(resolve) {
      let form = {};
      if (JSON.stringify(this.filterConfig) != "{}") {
        if (this.filterConfig.filterConfig.length > 0) {
          form.configRules = this.filterConfig.filterConfig.join();
        }
        if (this.filterConfig.managerUnit.length > 0) {
          form.managerUnits = this.filterConfig.managerUnit.join();
        }
        if (this.filterConfig.standardType != "") {
          form.standardType = this.filterConfig.standardType;
        }
      }
      //得到组织树的数据
      lazyClassifyTree(form)
        .then((res) => {
          let data = res.data || [];
          if (this.moveNode && data.length > 0) {
            this.setDisabledNode(data, resolve);
          } else {
            this.setTreeData(data, resolve);
          }
          //当有默认选中节点时不执行这一步
          if (this.selectNode) {
            let nodeId = this.selectNode.id || "";
            if (nodeId) {
              setTimeout(() => {
                this.treeNodeClick(this.selectNode);
              }, 200);
            } else {
              setTimeout(() => {
                this.defaultExpend(res.data[0]);
              }, 200);
            }
          } else {
            setTimeout(() => {
              this.defaultExpend(res.data[0]);
            }, 200);
          }
        })
        .catch((res) => {
          this.$message.error(res.description);
        });
    },
    //加载节点的子节点集合
    loadchildnode(node, resolve) {
      //得到组织树的数据
      let form = {
        parentId: node.data.id,
      };
      if (JSON.stringify(this.filterConfig) != "{}") {
        if (this.filterConfig.filterConfig.length > 0) {
          form.configRules = this.filterConfig.filterConfig.join();
        }
        if (this.filterConfig.managerUnit.length > 0) {
          form.managerUnits = this.filterConfig.managerUnit.join();
        }
        if (this.filterConfig.standardType != "") {
          form.standardType = this.filterConfig.standardType;
        }
      }
      lazyClassifyTree(form)
        .then((res) => {
          let data = res.data;
          if (this.moveNode && data.length > 0) {
            this.setDisabledNode(data, resolve);
          } else {
            this.setTreeData(data, resolve);
          }
          //搜索选中时，加载完最后一级节点选中以选择的节点
          if (node.level == this.parentNum - 1) {
            setTimeout(() => {
              this.treeNodeClick(this.selectNode);
            }, 500);
          }
        })
        .catch((res) => {
          this.$message.error(res.description);
        });
    },
    //设备树默认展开
    defaultExpend(node) {
      if (JSON.stringify(this.defaultNode) != "{}") {
        //当指定默认展开节点时
        if (this.defaultNode.level == 1) {
          this.updataData(this.defaultNode, true);
        } else {
          this.updataData(this.defaultNode, false);
        }
      } else {
        //未指定默认展开节点，就默认展开设备管理单位时用户所在单位的设备
        let params = {
          orgId: this.$store.getters.currentInfo.currOrg, //当前用户所在的组织
        };
        if (
          JSON.stringify(this.filterConfig) != "{}" &&
          this.filterConfig.managerUnit.length > 0
        ) {
          delete params.orgId;
          params.managerUnit = this.filterConfig.managerUnit[0];
        }
        getLeftUpperApi(params).then((res) => {
          if (res.data) {
            if (res.data.level == 1) {
              this.updataData(res.data, true);
            } else {
              this.updataData(res.data, false);
            }
          } else {
            this.treeNodeClick(node);
          }
        });
      }
    },

    //对数据进行处理并且设置树数据
    setTreeData(data, resolve) {
      const nodeList = this.selectedNodeList.map(item => {
        return item.equipId
      })
      // if(this.getHideRepeatNode() && nodeList.length > 0) {
      //   data = data.filter(i => !nodeList.includes(i.id))
      // }
      if (resolve) {
        let treeData = [];
        data.map((i) => {
          i.label = i.name;
          i.isLeaf = i.hasChildren ? false : true;
          i.cantSelected = this.getHideRepeatNode() && nodeList.includes(i.id);
          treeData.push(i);
        });
        setTimeout(() => {
          resolve(treeData);
        }, 100);
      }
    },
    updataData(node, isFirst) {
      let level = node ? node.level : 0;
      this.selectNode = node;
      this.expandKeys = [];
      if (!isFirst) {
        //判断是否是整棵树首次加载
        this.parentNum = level;
        if (node && level > 2) {
          //有默认节点且不是一级节点
          let isSave = isFirst ? false : true;
          this.expandTreeNode(node, isSave);
        } else {
          //没有默认节点或一级节点数据更新，此时整棵树的数据要重新加载
          //第一层级的节点全部刷新
          this.rootNode.childNodes = [];
          this.loadNode(this.rootNode, this.rootResolve); //再次执行懒加载的方法}
        }
      } else {
        this.treeNodeClick(node);
      }
    },
    // 移除节点
    removeData(node) {
      this.$refs.tree.remove(node)
    },

    //点击复选框时触发
    async checkClick(data, checked) {
      let checkedArr = checked.checkedKeys;
      if (this.optionalNum != 0) {
        if (checkedArr.length > this.optionalNum) {
          // this.$message.warning(
          //   "选择的节点树不得大于限定数量" + this.optionalNum + "个！"
          // );
          this.$message.warning("只能选择一个节点进行移动！");
          checkedArr = await this.arrRemove(checkedArr, data.id);
          this.$refs.tree.setCheckedKeys(checkedArr);
        }
      }
    },
    //移除掉刚选中的节点
    arrRemove(arr, key) {
      let resArr = [];
      arr.map((i) => {
        if (i != key) {
          resArr.push(i);
        }
      });
      return resArr;
    },
    //获取选中的node的Keys，用于菜单权限控制
    getCheckedKeys() {
      let halfData = this.$refs.tree.getHalfCheckedKeys(); //半选中状态的节点
      let checkedDataObj = this.$refs.tree.getCheckedNodes(); //全选中状态的节点
      let checkedData = checkedDataObj.map((i) => {
        return i.id;
      });
      let data = halfData.concat(checkedData); //合并两个数组
      return data;
    },
    getCheckedNodes() {
      let checkedDataObj = this.$refs.tree.getCheckedNodes(); //全选中状态的节点
      return checkedDataObj;
    },
  },
};
</script>
<style lang="less" scoped>
.org-member-tree .el-tree-node__content {
  border-left: 3px solid transparent;
}
.treeTitleDiv {
  text-align: left;
  padding: 20px 0 15px 0;
  display: flex;
  justify-content: space-between;
  .treeTitle {
    font-weight: 500;
    color: #333333;
  }
  .treeTitle:before {
    margin-right: 12px;
    width: 4px;
    height: 18px;
    background-color: #0d60b4;
    display: inline-block;
    content: "";
  }
}
/deep/.el-tree--highlight-current
  .el-tree-node.is-current
  > .el-tree-node__content {
  background-color: #E1EFFC !important;
  border-left: 3px solid #2c77f4;
  color: #0b5eec; 
}
.el-tree-node__expand-icon + .custom-tree-node {
  font-weight: 700;
}
.is-leaf + .custom-tree-node {
  font-weight: 400;
}
.org-member-tree {
  .filter__box {
    padding: 0px 0px 10px 0px;
  }
  .showSearch {
    display: flex;
  }
  .inline-input {
    width: 100%;
  }
  .treeInput {
    width: 100%;
  }
  .tree__box {
    height: calc(100% - 110px);
    overflow: auto;
    padding-top: 5px;
    overflow-x: auto;
    /deep/ .el-tree-node.is-expanded > .el-tree-node__children {
      display: inline;
    }
  }
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    //justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
    .el-button {
      margin-right: 10px;
      margin-left: 0px;
    }
  }
}
/deep/ .list-table-search--item {
  width: 20% !important;
}
/deep/ .list-table-search--item .item-input {
  width: 100% !important;
}
/deep/ .el-input-group__append > .el-button {
  padding: 0 15px;
}
.advanceSearch{
  width: 100%;
  height: calc(100% - 20px);
}
.number{
  font-size: 14px;
  font-weight: 400;
}
</style>
